package cn.ffcs.bpmpvc.web;

import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;
import org.echoice.paper.PageBean;
import org.echoice.paper.PageNavi;
import org.echoice.util.DateUtil;

import cn.ffcs.bpm.model.ProcTranRecord;
import cn.ffcs.bpm.model.TransactProcessStatus;
import cn.ffcs.bpmpvc.services.AppBusinessReqService;
import cn.ffcs.bpmpvc.svc.ProcessPvcService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.svc.TaskService;
import cn.ffcs.bpmpvc.web.forms.FlowTaskForm;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.bpmpvc.web.views.ProcessView;
import cn.ffcs.bpmpvc.web.views.TaskView;
import cn.ffcs.businessrequest.model.BusinessReason;
import cn.ffcs.businessrequest.model.BusinessRequest;
import cn.ffcs.businessrequest.model.ProdAdvReq;
import cn.ffcs.businessrequest.model.ReqDocu;
import cn.ffcs.organ.model.Organization;
import cn.ffcs.organ.model.Person;
import cn.ffcs.security.model.User;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.util.context.ApplicationContextUtil;

/**
 * yedw
 * @author Administrator
 *
 */
public class FlowRequestAction extends FlowAppBaseAction<TransactProcessStatus>
{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ProcessPvcService processPvcService;
    private TaskService taskService;
    private AppBusinessReqService appBusinessReqService;
    private ProdAdvReq prodAdvReq;
    private BusinessRequest businessRequest;
    /** 需求类型 **/
    private List<Dict> types;
    /** 重要性 **/
    private List<Dict> importances;
    
    /** 附件上传 **/
    private List<File> uploads;
    private List<String> filetype;
    /**要删除的文件**/
    private List<String> delDocumentIds;
    private String flowTaskId;    
    private String processId;
    private String procinstId;
    private FlowTaskForm flowTaskForm;
    private static final String ENTER_CLIENT_CODEID="FJ06";
    private static final String ENTER_POC_CODEID="FJ07";
    //号百公司ID
    public static final String HAOBAI_ID="1634";
    //号百公司领导所在部门
    public static final String HAOBAI_LEADER_ID="1640";
    private static final String TO_ENTER_CLIENT="to_enterClient";
    
    public String applySelect(){
    	User user =ApplicationContextUtil.getUserContextObject().getCurrUser();
    	Organization startDept=getAppBusinessReqService().getOrgByPerson(user.getPerson());
    	String startDeptId=String.valueOf(startDept.getId());
    	Organization enterOrg=getAppBusinessReqService().getAppBusinessReqDao().getOrganizationByCodeId(ENTER_POC_CODEID);
    	String supId=String.valueOf(enterOrg.getId());
    	if(supId.equals(startDeptId)||supId.equals(startDept.getSuperior())){
    		return "applySelect";
    	}
    	//boolean isProd=getAppBusinessReqService().checkPersonIsProd(user.getPersonID());
    	//if(isProd){
    	//	return "applySelect";
    	//}
    	return applyInit();
    }
    
    public String applyInit(){
        initDict();
        String processId=getAppBusinessReqService().getFlowImproveReqCheckProcessId();        
        User user =ApplicationContextUtil.getUserContextObject().getCurrUser();
        //根据当前用户取所在的组，如果是一级部门，直接到需求审核，如果不是一级部门先领导审核        
        Organization startDept=getAppBusinessReqService().getOrgByPerson(user.getPerson());
        ProcessView processView=null;
        /****/
        int orgLevel=startDept.getOrgLevel();
        if(orgLevel<=2){
        	processView=getProcessPvcService().getInitProcessInfo(processId,"to_response",user);
        }else{
        	//TODO by junyang 2011-02-10 如果是省政企客户部，需要先需求管理员审核98
        	//FJ06        	
        	String superior=startDept.getSuperior();
        	Organization enterOrg=getAppBusinessReqService().getAppBusinessReqDao().getOrganizationByCodeId(ENTER_CLIENT_CODEID);
    		String orgId=String.valueOf(enterOrg.getId());
        	if(orgId.equals(superior)){
        		processView=getProcessPvcService().getInitProcessInfo(processId,TO_ENTER_CLIENT,user);
        	}else{
        		processView=getProcessPvcService().getInitProcessInfo(processId,"to_deptCheck",startDept);
        	}
        }
        prodAdvReq=new ProdAdvReq();
        prodAdvReq.setStartPerson(user.getPerson());
        prodAdvReq.setStartDept(startDept);
        Dict dict=new Dict();
        dict.setId(62);
        prodAdvReq.setImportance(dict);
        String title=ApplicationContextUtil.getHttpServletRequest().getParameter("prodAdvReq.name");
        prodAdvReq.setName(title);
        //得到产品经理角色用户
        List<Person> prodList=appBusinessReqService.findProdListByRole();
        ApplicationContextUtil.getHttpServletRequest().setAttribute("prodList", prodList);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("processView", processView);
        return "initApply";
    }
    /**
     * 产品经理发起快速需求支撑流程
     * @return
     */
    public String applyInitFastFlow(){
        initDict();
        String processId=getAppBusinessReqService().getFlowFastImproveReqProcessId();
        User user =ApplicationContextUtil.getUserContextObject().getCurrUser();        
        Organization startDept=getAppBusinessReqService().getOrgByPerson(user.getPerson());
        ProcessView processView=null;        
        processView=getProcessPvcService().getInitProcessInfo(processId,null,startDept);
        prodAdvReq=new ProdAdvReq();
        prodAdvReq.setStartPerson(user.getPerson());
        prodAdvReq.setStartDept(startDept);
        Dict dict=new Dict();
        dict.setId(62);
        prodAdvReq.setImportance(dict);
        String title=ApplicationContextUtil.getHttpServletRequest().getParameter("prodAdvReq.name");
        prodAdvReq.setName(title);
        //得到产品经理角色用户
        List<Person> prodList=appBusinessReqService.findProdListByRole();
        ApplicationContextUtil.getHttpServletRequest().setAttribute("prodList", prodList);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("processView", processView);
        return "initApplyFast";
    }
    
    public String saveStartFlow(){
        String isCommitS=ApplicationContextUtil.getContextObject("isCommit");
        boolean isCommit=Boolean.valueOf(isCommitS);
        setAdvanTime(prodAdvReq);
        prodAdvReq.setEnd(cn.ffcs.util.converter.DateUtil.getMaxDate());
        User user =ApplicationContextUtil.getUserContextObject().getCurrUser();
        HttpServletRequest req=ApplicationContextUtil.getHttpServletRequest();
        List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
        String processId=req.getParameter("processId");
        //String processId=getAppBusinessReqService().getFlowImproveReqCheckProcessId();
        //对于时间的处理
        //TODO by junayng 2011-06-22
		prodAdvReq.replaceContentNtoBR();
        if(isCommit){
            returnMsg="业务需求单提交成功";
        }else{
            returnMsg="业务需求单记录保存成功";
        }
        try{
            @SuppressWarnings("unused")
			ProcTranRecord procTranRecord=getAppBusinessReqService().saveProdReqAndStartFlow(processId, user.getPerson(), nextTasksList, isCommit, prodAdvReq, uploads, filetype);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            returnMsg=e.getMessage();
        }
        return "jumpMsg";
    }
    
    /**
     * 查看明细，进入办理
     * TODO 请输入方法说明
     * @return
     */
    public String showDetail(){
        initDict();
        String procinstId=ApplicationContextUtil.getContextObject("procinstId");
        Integer procInstId=Integer.valueOf(procinstId);
        //取业务数据
        prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReq(procInstId);
        
        String toPage=ApplicationContextUtil.getContextObject("toPage");
        TaskView taskView=null;
        /****/
        if("bsImprovementStart".equals(toPage)){
        	Organization startDept=prodAdvReq.getStartDept();
        	int orgLevel=startDept.getOrgLevel();
        	if(orgLevel<=2){
        		taskView=getTaskService().getTaskView(flowTaskId,"to_response",startDept);
        	}else{
        		String superior=startDept.getSuperior();
        		Organization enterOrg=getAppBusinessReqService().getAppBusinessReqDao().getOrganizationByCodeId(ENTER_CLIENT_CODEID);
        		String orgId=String.valueOf(enterOrg.getId());
        		if(orgId.equals(superior)){
        			taskView=getTaskService().getTaskView(flowTaskId,TO_ENTER_CLIENT,startDept);
        		}else{
        			taskView=getTaskService().getTaskView(flowTaskId,"to_deptCheck",startDept);
        		}
        	}
        }else if(TO_ENTER_CLIENT.equals(toPage)){
        	Organization startDept=prodAdvReq.getStartDept();
        	taskView=getTaskService().getTaskView(flowTaskId,null,startDept);
        } else{
        	taskView=getTaskService().getTaskView(flowTaskId);
        }
        
        //taskView=getTaskService().getTaskView(flowTaskId);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", taskView);
        //取得已经上传文档
        List<ReqDocu> reqDocuList=getAppBusinessReqService().getAppBusinessReqDao().findDocuList(procInstId);
        
        ApplicationContextUtil.getHttpServletRequest().setAttribute("reqDocuList", reqDocuList);
        //判断该步骤是否已上传文档start
        judgeDocuIsUpload(taskView, reqDocuList);
        setRepDocTableStyleList(reqDocuList);
        //end
        //return "/bpm/pvc/bsReqDetailStart.jsp";
        String taskType=taskView.getProcTranRecord().getTaskType();
        if("03".equalsIgnoreCase(taskType)){
        	String taskAppExt=taskView.getProcTranRecord().getTaskAppExt();
        	if(StringUtils.isNotBlank(taskAppExt)){
        		return taskAppExt;
        	}
        	
        	return "detailForRedo";
        }
        
        if(StringUtils.isNotBlank(toPage)){
        	if("bsImprovementStart".equals(toPage)){
        		//得到产品经理角色用户
        		prodAdvReq.replaceContentBRtoN();
                List<Person> prodList=appBusinessReqService.findProdListByRole();
                ApplicationContextUtil.getHttpServletRequest().setAttribute("prodList", prodList);
                prodAdvReq.setRep(false);
        	}else if("to_enterClient".equals(toPage)){
        		return "detail";
        	}
            return toPage;
        }
        return "detail";
    }

    /**
     * 查看或启动需求单
     * @return
     */
    public String showInfo(){
        //取业务数据
    	
        String procInstIdS=ApplicationContextUtil.getContextObject("procinstId");
        if(StringUtils.isNotBlank(procInstIdS)){
        	Integer procInstId=Integer.valueOf(procInstIdS);
            prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReq(procInstId);
            //取得已经上传文档
            List<ReqDocu> reqDocuList=getAppBusinessReqService().getAppBusinessReqDao().findDocuList(procInstId);
            setRepDocTableStyleList(reqDocuList);
            ApplicationContextUtil.getHttpServletRequest().setAttribute("reqDocuList", reqDocuList);
            //取得流程实例及任务信息
            ProcessInstView processInstView=getProcessPvcService().getProcessInstView(procInstId);
            
            ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", processInstView);
            setProcessInstTaskInfo(getTaskService(),processInstView,procInstIdS);
            //取得需求单强制结束原因
    		BusinessReason businessReason=getAppBusinessReqService().getAppBusinessReqDao().findBusinessReason(procInstIdS);
    		ApplicationContextUtil.getHttpServletRequest().setAttribute("businessReason", businessReason);
        }else{
        	//兼容以前有审核单
        	String reqIdS=ApplicationContextUtil.getContextObject("reqId");
        	prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReqById(Integer.valueOf(reqIdS));
        	//取得已经上传文档
            List<ReqDocu> reqDocuList=getAppBusinessReqService().getAppBusinessReqDao().findDocuListByRefIdAndType(prodAdvReq.getId(), prodAdvReq.getClass().getName());
            setRepDocTableStyleList(reqDocuList);
            ApplicationContextUtil.getHttpServletRequest().setAttribute("reqDocuList", reqDocuList);
        }
        
    	return "appInfoDetail";
    }
    
    public String exportExcel(){
        //取业务数据
    	
        String procInstIdS=ApplicationContextUtil.getContextObject("procinstId");
        List<ReqDocu> reqDocuList=null;
        
        ProcessInstView processInstView=null;
        BusinessReason businessReason=null;
        if(StringUtils.isNotBlank(procInstIdS)){
        	Integer procInstId=Integer.valueOf(procInstIdS);
            prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReq(procInstId);
            //取得已经上传文档
            reqDocuList=getAppBusinessReqService().getAppBusinessReqDao().findDocuList(procInstId);
            setRepDocTableStyleList(reqDocuList);
            //取得流程实例及任务信息
            processInstView=getProcessPvcService().getProcessInstView(procInstId);
            
            ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", processInstView);
            setProcessInstTaskInfo(getTaskService(),processInstView,procInstIdS);
            //取得需求单强制结束原因
    		businessReason=getAppBusinessReqService().getAppBusinessReqDao().findBusinessReason(procInstIdS);
        }else{
        	//兼容以前有审核单
        	String reqIdS=ApplicationContextUtil.getContextObject("reqId");
        	prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReqById(Integer.valueOf(reqIdS));
        	//取得已经上传文档
            reqDocuList=getAppBusinessReqService().getAppBusinessReqDao().findDocuListByRefIdAndType(prodAdvReq.getId(), prodAdvReq.getClass().getName());
            setRepDocTableStyleList(reqDocuList);
        }
        try{
        	
        	HttpServletResponse response = ApplicationContextUtil.getHttpServletResponse();
        	response.setContentType("application/stream;charset=UTF-8");
    		response.setHeader("Content-Disposition", "attachment; filename=\""+ URLEncoder.encode(prodAdvReq.getName()+".xls", "UTF-8") + "\"");
    		OutputStream os = response.getOutputStream();
    		WritableWorkbook workbook = Workbook.createWorkbook(os);
    		WritableSheet sheet = workbook.createSheet("需求单信息", 0);
    		//定义字体信息
    		jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES,14,WritableFont.BOLD);
    		jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf); 
    		wcfF.setBackground(jxl.format.Colour.ICE_BLUE);
    		
    		//
    		jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.TIMES,12); 
    		jxl.write.WritableCellFormat wcfFc = new jxl.write.WritableCellFormat(wfc);
    		
    		jxl.write.WritableCellFormat wcfFh = new jxl.write.WritableCellFormat(wfc);
    		wcfFh.setAlignment(Alignment.RIGHT);
    		
    		
    		jxl.write.WritableFont wfcGrid = new jxl.write.WritableFont(WritableFont.TIMES,12,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,Colour.RED); 
    		jxl.write.WritableCellFormat wcfFcGrid = new jxl.write.WritableCellFormat(wfcGrid);
    		
    		//sheet.setRowView(0,500);//高
    		sheet.setColumnView(0, 20);//宽
    		sheet.setColumnView(3, 16);//宽
    		
    		sheet.setColumnView(1, 20);//宽
    		sheet.setColumnView(2, 20);//宽
    		sheet.setColumnView(4, 20);//宽
    		sheet.setColumnView(5, 20);//宽
    		sheet.setColumnView(6, 20);//宽
    		sheet.setColumnView(7, 20);//宽
    		//分类一
    		sheet.mergeCells(0, 0, 7, 0);
    		int row=0;
    		Label label = new Label(0, 0, "流程信息",wcfF); //put a label in cell A1, Label(column,row)
    		sheet.addCell(label);
    		row++;
    		
    		writeLabel(sheet,row,"当前流程：",processInstView.getProcessConfig().getName(),wcfFh,wcfFc);
    		row++;
    		//
    		writeLabel(sheet,row, "当前状态：","","当前办理人：","",wcfFh,wcfFc);
    		row++;
    		//
    		String beginTime=DateUtil.format(processInstView.getProcessStatus().getBegin(), "yyyy-MM-dd HH:mm");
    		String endTime="";
    		if(processInstView.getProcessStatus().getEnd()!=null){
    			endTime=DateUtil.format(processInstView.getProcessStatus().getEnd(), "yyyy-MM-dd HH:mm");
    		}
    		writeLabel(sheet,row, "开如时间：",beginTime,"结束时间：",endTime,wcfFh,wcfFc);
    		row++;
    		row++;
    		//分类二
    		sheet.mergeCells(0, row, 7, row);
    		label = new Label(0, row, "基本信息",wcfF); //put a label in cell A1, Label(column,row)
    		sheet.addCell(label);
    		row++;
    		//
    		writeLabel(sheet,row,"名称：",processInstView.getProcessConfig().getName(),wcfFh,wcfFc);
    		row++;
    		//
    		writeLabel(sheet,row, "发 起 人：",prodAdvReq.getStartPerson().getName(),"发起部门：",prodAdvReq.getStartDept().getFullName(),wcfFh,wcfFc);
    		row++;
    		//
    		writeLabel(sheet,row,"需求单号：",prodAdvReq.getReqCode(),wcfFh,wcfFc);
    		row++;
    		
    		//
    		beginTime="";
    		if(prodAdvReq.getAdvanTime()!=null){
    			beginTime=DateUtil.format(prodAdvReq.getAdvanTime(), "yyyy年MM月dd日");
    		}
    		endTime="";
    		if(prodAdvReq.getBegin()!=null){
    			endTime=DateUtil.format(prodAdvReq.getBegin(), "yyyy年MM月dd日");
    		}
    		
    		
    		writeLabel(sheet,row, "期户完成时间：",beginTime,"发起时间：",endTime,wcfFh,wcfFc);
    		row++;
    		
    		String tmp1="";
    		
    		if(prodAdvReq.getProdPerson()!=null){
    			tmp1=prodAdvReq.getProdPerson().getName();
    		}
    		
    		String tmp2="";
    		
    		if(prodAdvReq.getProdDept()!=null){
    			tmp2=prodAdvReq.getProdDept().getFullName();
    		}
    		
    		writeLabel(sheet,row, "产品经理：",tmp1,"产品部门：",tmp2,wcfFh,wcfFc);
    		row++;
    		
    		//
    		
    		writeLabel(sheet,row, "需求类别：",prodAdvReq.getType().getName(),"重要性：",prodAdvReq.getImportance().getName(),wcfFh,wcfFc);
    		row++;
    		
    		//
    		String content=StringUtils.replace(prodAdvReq.getContent(), "<br/>", "\n");
    		sheet.setRowView(row,1000);
    		//wcfFc.setWrap(true);
    		writeLabel(sheet,row,"内    容：",content,wcfFh,wcfFc);
    		row++;
    		
    		writeLabel(sheet,row,"业务标签：",prodAdvReq.getBusinessTag(),wcfFh,wcfFc);
    		row++;
    		
    		
    		String checkStr="";
    		if("PASS".equals(prodAdvReq.getTranStatus())||"DOPASS".equals(prodAdvReq.getTranStatus())){
    			checkStr="通过";
    		}else if("NOPASS".equals(prodAdvReq.getTranStatus())){
    			checkStr="不通过";
    		}else if("REFUSE".equals(prodAdvReq.getTranStatus())){
    			checkStr="拒绝";
    		}
    		
    		writeLabel(sheet,row,"审核结果：",checkStr,wcfFh,wcfFc);
    		row++;
    		
    		label = new Label(0, row, "附件：",wcfFh); 
    		sheet.addCell(label);
    		//row++;
    		
    		//
    		String gridLabArr[]=new String[]{"办理步骤","附件名称","附件类型","上传人员","上传时间"};
    		for (int i = 0; i < gridLabArr.length; i++) {
    			label = new Label(i+1, row, gridLabArr[i],wcfFcGrid); 
        		sheet.addCell(label);
			}
    		row++;
    		
    		//附件记录
    		for (ReqDocu reqDocu : reqDocuList) {
    			if(StringUtils.isNotBlank(reqDocu.getLength())){
    				int length=Integer.parseInt(reqDocu.getLength());
    				if(length>1){
    					sheet.mergeCells(1, row, 1, row+length);
    				}
    				
    				label = new Label(1, row, reqDocu.getProcessDetail().getName(),wcfFc); 
            		sheet.addCell(label);
    			}
    			
    			label = new Label(2, row, reqDocu.getFullName(),wcfFc);
        		sheet.addCell(label);
        		
        		label = new Label(3, row, reqDocu.getDocType().getName(),wcfFc); 
        		sheet.addCell(label);
        		
        		label = new Label(4, row, reqDocu.getCreator(),wcfFc); //
        		sheet.addCell(label);
        		
        		beginTime=DateUtil.format(reqDocu.getBegin(), "yyyy-MM-dd HH:mm");
        		label = new Label(5, row, beginTime,wcfFc); //
        		sheet.addCell(label);
    			row++;
    		}
    		//end
    		row++;
    		//分类三
    		sheet.mergeCells(0, row, 7, row);
    		label = new Label(0, row, "办理过程",wcfF); //
    		sheet.addCell(label);
    		row++;
    		
    		gridLabArr=new String[]{"序号","办理步骤","办理事项","办理意见","","办理人员","到达时间","办理时间"};
     		for (int i = 0; i < gridLabArr.length; i++) {
     			
     			label = new Label(i, row, gridLabArr[i],wcfFcGrid); //
         		sheet.addCell(label);
 			}
     		sheet.mergeCells(3, row, 4, row);
     		row++;
     		int i=1;
     		for (ProcTranRecord task : processInstView.getFlowTaskList()) {
     			label = new Label(0, row, String.valueOf(i),wcfFc); //
        		sheet.addCell(label);
        		
        		label = new Label(1, row, task.getProcessStep().getName(),wcfFc); //
        		sheet.addCell(label);
        		
        		label = new Label(2, row, task.getMatters(),wcfFc); //
        		sheet.addCell(label);
        		
        		sheet.mergeCells(3, row, 4, row);
        		label = new Label(3, row, StringUtils.replace(task.getTransactInfo(), "<br />", "\n"),wcfFc); //
        		sheet.addCell(label);
        		
        		
        		label = new Label(5, row, task.getTransactor().getName(),wcfFc); 
        		sheet.addCell(label);
        		
        		beginTime=DateUtil.format(task.getReceiveTime(), "yyyy-MM-dd HH:mm");
        		label = new Label(6, row, beginTime,wcfFc); //
        		sheet.addCell(label);
        		
        		endTime="";
        		if(task.getTransactTime()!=null){
        			endTime=DateUtil.format(task.getTransactTime(), "yyyy-MM-dd HH:mm");
        		}
        		label = new Label(7, row, endTime,wcfFc); //
        		sheet.addCell(label);
        		
        		i++;
        		row++;
			}
     		
    		workbook.write();
    		workbook.close();
			//os.close();
        }catch (Exception e) {
			// TODO: handle exception
        	
		}
		return null;
    }
    

    
    /**
     * 跳转到启动流程页面
     * @return
     */
    public String toStartReq(){
    	//取业务数据
		initDict();
		//得到产品经理角色用户
        List<Person> prodList=appBusinessReqService.findProdListByRole();
        ApplicationContextUtil.getHttpServletRequest().setAttribute("prodList", prodList);
        //TODO by junyang 2010-05-11
        String processId=getAppBusinessReqService().getFlowImproveReqProcessId();
        ProcessView processView=getProcessPvcService().getInitProcessInfo(processId);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("processView", processView);
        //end
    	showInfo();
    	return "toStartReq";
    }
    /**
     * 启动产品改进需求流程
     * @return
     */
    public String startReq(){
    	HttpServletRequest request = ApplicationContextUtil.getHttpServletRequest();
    	String reqId=request.getParameter("reqId");
    	String processId=getAppBusinessReqService().getFlowImproveReqProcessId();
    	BusinessRequest businessRequest =getAppBusinessReqService().startReq(reqId, processId,request);
    	this.returnMsg="产品优化需求流程启动成功！已提交至 "+businessRequest.getProdPerson().getName();
    	return "jumpMsg";
    }
    /**
     * 保存数据提交任务
     * TODO 请输入方法说明
     * @return
     */
    public String saveOrCommitTask(){
    	String procinstId=ApplicationContextUtil.getContextObject("procinstId");
        String isCommitS=ApplicationContextUtil.getContextObject("isCommit");
        boolean isCommit=Boolean.valueOf(isCommitS);//保存
        HttpServletRequest req=ApplicationContextUtil.getHttpServletRequest();
        //ApplicationContextUtil.getHttpServletResponse().sendRedirect(arg0);
        List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
        String content=req.getParameter("commentComtent");
        setCommitTaskMsg(isCommit);
        String auditResult=req.getParameter("rodAdvReq.tranStatus");//评审结果
        //System.out.println(auditResult);
        if(StringUtils.isNotBlank(auditResult)){
        	ProdAdvReq prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReq(Integer.valueOf(procinstId));
        	prodAdvReq.setTranStatus(auditResult);
        	prodAdvReq.setEnd(cn.ffcs.util.converter.DateUtil.getMaxDate());
        	getAppBusinessReqService().getAppBusinessReqDao().save(prodAdvReq);
        	if(isCommit){
            	if("PASS".equals(auditResult)||"DOPASS".equals(auditResult)){
            		String redirectUrl="bpm/flowReq_toStartReq.action?procinstId="+procinstId+"&reqId="+prodAdvReq.getId();
            		req.setAttribute("redirectUrl", redirectUrl);
            		//将评审传阅给需求发起人
            	}
            }
        }
        try{
            getAppBusinessReqService().saveProdDataAndCommitTask(flowTaskId, content, nextTasksList, isCommit, uploads, filetype,delDocumentIds);
            
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            returnMsg=e.getMessage();
        }
        return "jumpMsg";
    }
    
    public String saveCheckOrCommitTask(){
    	String procinstId=ApplicationContextUtil.getContextObject("procinstId");
        String isCommitS=ApplicationContextUtil.getContextObject("isCommit");
        boolean isCommit=Boolean.valueOf(isCommitS);//保存
        HttpServletRequest req=ApplicationContextUtil.getHttpServletRequest();
        List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
        String content=req.getParameter("commentComtent");
        setCommitTaskMsg(isCommit);
        String auditResult=req.getParameter("rodAdvReq.tranStatus");//评审结果
        try{
            getAppBusinessReqService().saveProdCheckAndCommitTask(flowTaskId, content, nextTasksList, isCommit,procinstId,auditResult,uploads, filetype,delDocumentIds);
            if(isCommit){
            	if("PASS".equals(auditResult)||"DOPASS".equals(auditResult)){
            		ProdAdvReq prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReq(Integer.valueOf(procinstId));
            		String redirectUrl="bpm/flowReq_toStartReq.action?procinstId="+procinstId+"&reqId="+prodAdvReq.getId();
            		req.setAttribute("redirectUrl", redirectUrl);
            	}
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            returnMsg=e.getMessage();
        }
        return "jumpMsg";
    }
    /**
     * 发起人修改保存数据
     * TODO 请输入方法说明
     * @return
     */
    public String updateBROrCommitTask(){
        //保存业务数据
        String procinstId=ApplicationContextUtil.getContextObject("procinstId");
        ProdAdvReq prodAdvReq=getAppBusinessReqService().getAppBusinessReqDao().getProdAdvReq(Integer.valueOf(procinstId));
        prodAdvReq.setName(this.prodAdvReq.getName());
        prodAdvReq.setContent(this.prodAdvReq.getContent());
        setAdvanTime(prodAdvReq);
        prodAdvReq.setProdPerson(this.prodAdvReq.getProdPerson());
        if(this.prodAdvReq.getProdPerson()!=null&&this.prodAdvReq.getProdPerson().getId()!=null){
        	prodAdvReq.setProdDept(getAppBusinessReqService().getOrgByPerson(this.prodAdvReq.getProdPerson()));
        	String prodIdStr = prodAdvReq.getProdPerson().getId().toString();
			getTaskService().saveSwimlance(prodIdStr, "prodPersonSwim", Integer.valueOf(procinstId));
        }else{
        	prodAdvReq.setProdPerson(null);
        }
        
        prodAdvReq.setImportance(this.prodAdvReq.getImportance());
        prodAdvReq.setType(this.prodAdvReq.getType());
        prodAdvReq.replaceContentNtoBR();
        getAppBusinessReqService().getAppBusinessReqDao().save(prodAdvReq);
        
        return saveOrCommitTask();
    }

    @SuppressWarnings("unchecked")
	public String searchProdAdvReqList(){
    	if(flowTaskForm==null){
    		flowTaskForm=new FlowTaskForm();
    	}
		User user =ApplicationContextUtil.getUserContextObject().getCurrUser();
		flowTaskForm.setUserId(user.getPerson().getId().toString());
    	HttpServletRequest request=ApplicationContextUtil.getHttpServletRequest();
    	PageBean pageBean=getAppBusinessReqService().getAppBusinessReqDao().queryPageProdAdvReqList(this.flowTaskForm, PageNavUtil.getPageNo(request), PageNavUtil.getPageSize(request));
    	@SuppressWarnings("unused")
		List<ProdAdvReq> list=pageBean.getDataList();
//    	if(list!=null&&list.size()>0){
//    		for (ProdAdvReq prodAdvReq : list) {
//            	if(prodAdvReq.getProcinstId()!=null){
//            		List<Node> nodeList=getTaskService().getFlowPvcDao().findRunNodeList(prodAdvReq.getProcinstId().toString());
//            		if(nodeList!=null&&nodeList.size()>0){
//            			String currStatus="";
//            			for (Node node : nodeList) {
//            				currStatus+=node.getName()+"、";
//            			}
//            			currStatus=currStatus.substring(0,currStatus.length()-1);
//            			prodAdvReq.setCurStatus(currStatus);
//            		}
//            	}
//    		}
//    	}
    	request.setAttribute("bsReqlist", pageBean.getDataList());
        String pageNaviStr=PageNavi.getPageNaviText(request, pageBean);
        request.setAttribute("pageNaviStr", pageNaviStr);
    	return "bsReqAdviceList";
    }

    public String searchProdAdvReqFJList(){
    	if(flowTaskForm==null){
    		flowTaskForm=new FlowTaskForm();
    	}
    	flowTaskForm.setState("'PASS','DOPASS'");
    	flowTaskForm.setOpType("NOTFJHB");
    	HttpServletRequest request=ApplicationContextUtil.getHttpServletRequest();
    	PageBean pageBean=getAppBusinessReqService().getAppBusinessReqDao().queryPageProdAdvReqList(this.flowTaskForm, PageNavUtil.getPageNo(request), PageNavUtil.getPageSize(request));
        request.setAttribute("bsReqlist", pageBean.getDataList());
        String pageNaviStr=PageNavi.getPageNaviText(request, pageBean);
        request.setAttribute("pageNaviStr", pageNaviStr);
    	return "bsReqAdviceFJList";
    }
    
	private void setAdvanTime(ProdAdvReq prodAdvReq) {
		String advanTime=ApplicationContextUtil.getContextObject("prodAdvReq.advanTime");
        if(StringUtils.isNotBlank(advanTime)){
        	try {
        		prodAdvReq.setAdvanTime(DateUtil.parse(advanTime, "yyyy-MM-dd"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}

    private void initDict(){
        String reqNewProdtypes = "REQ_PROD_TYPE";
        String reqImportType = "REQ_IMPORT_TYPE";
        types=getAppBusinessReqService().getAppBusinessReqDao().findDict(reqNewProdtypes);        
        importances=getAppBusinessReqService().getAppBusinessReqDao().findDict(reqImportType);
    }

    /**
     * 强制结束
     * @return
     */
    public String toEnd(){
    	 String procinstId=ApplicationContextUtil.getContextObject("procinstId");
         Integer procInstId=Integer.valueOf(procinstId);
//         businessRequest=getAppBusinessReqService().getAppBusinessReqDao().getBusinessRequest(procInstId);
         getAppBusinessReqService().toEnd(procInstId,null);
         this.returnMsg="已成功结束此需求单！";
    	return "jumpMsg";
    }
    /**
     * 删除需求单
     * @return
     */
    public String toDelete(){
		String procinstId=ApplicationContextUtil.getContextObject("procinstId");
	    Integer procInstId=Integer.valueOf(procinstId);
	    getAppBusinessReqService().delete(procInstId,"2",null);
	    this.returnMsg="已成功删除此需求单！";
    	return "jumpMsg";
    }
    /**
     * 转向需求单 发起评审,选择评人员
     * @return
     */
    public String toAssignTaskReview(){
    	return "taskReadingToDoForReview";
    }

    /**
     * 转向需求单 发起评审
     * @return
     */
    public String commitAssignTaskReview(){
    	//
        String content=ApplicationContextUtil.getContextObject("commentComtent");
        String taskAppExt=ApplicationContextUtil.getContextObject("taskAppExt");
        String userIds[]=ApplicationContextUtil.getHttpServletRequest().getParameterValues("userId");
        
        getTaskService().taskReadingToDo(flowTaskId, content, userIds,taskAppExt);
        this.returnMsg="已经将需求发给相应的评审人，请等待评审人员反馈！";
        return SUCCESS;
    }
    /**
     * 填写内容及意见
     * @return
     */
    public String commitTaskReviewComment(){
    	String content=ApplicationContextUtil.getContextObject("commentComtent");
    	String reviewOption=ApplicationContextUtil.getContextObject("reviewOption");
    	content="评审结果："+reviewOption+"<br />评审意见："+content;
    	try{
    		getTaskService().completeTask(flowTaskId, content, null);
    		setCommitTaskMsg(true);
    	}catch (Exception e) {
			// TODO: handle exception
    		this.returnMsg=e.getMessage();
		}
        return "jumpMsg";
    }
    
    public ProcessPvcService getProcessPvcService()
    {
        return processPvcService;
    }

    public void setProcessPvcService(ProcessPvcService processPvcService)
    {
        this.processPvcService = processPvcService;
    }

    public TaskService getTaskService()
    {
        return taskService;
    }

    public void setTaskService(TaskService taskService)
    {
        this.taskService = taskService;
    }

    public BusinessRequest getBusinessRequest()
    {
        return businessRequest;
    }

    public void setBusinessRequest(BusinessRequest businessRequest)
    {
        this.businessRequest = businessRequest;
    }

    public AppBusinessReqService getAppBusinessReqService()
    {
        return appBusinessReqService;
    }

    public void setAppBusinessReqService(AppBusinessReqService appBusinessReqService)
    {
        this.appBusinessReqService = appBusinessReqService;
    }

    public List<Dict> getTypes()
    {
        return types;
    }

    public void setTypes(List<Dict> types)
    {
        this.types = types;
    }

    public List<Dict> getImportances()
    {
        return importances;
    }

    public void setImportances(List<Dict> importances)
    {
        this.importances = importances;
    }

    public List<String> getFiletype()
    {
        return filetype;
    }

    public void setFiletype(List<String> filetype)
    {
        this.filetype = filetype;
    }

    public List<File> getUploads()
    {
        return uploads;
    }

    public void setUploads(List<File> uploads)
    {
        this.uploads = uploads;
    }

    public String getProcessId()
    {
        return processId;
    }

    public void setProcessId(String processId)
    {
        this.processId = processId;
    }

    public String getFlowTaskId()
    {
        return flowTaskId;
    }

    public void setFlowTaskId(String flowTaskId)
    {
        this.flowTaskId = flowTaskId;
    }

    public List<String> getDelDocumentIds()
    {
        return delDocumentIds;
    }

    public void setDelDocumentIds(List<String> delDocumentIds)
    {
        this.delDocumentIds = delDocumentIds;
    }

	public ProdAdvReq getProdAdvReq() {
		return prodAdvReq;
	}

	public void setProdAdvReq(ProdAdvReq prodAdvReq) {
		this.prodAdvReq = prodAdvReq;
	}

	public String getProcinstId() {
		return procinstId;
	}

	public void setProcinstId(String procinstId) {
		this.procinstId = procinstId;
	}

	public FlowTaskForm getFlowTaskForm() {
		return flowTaskForm;
	}

	public void setFlowTaskForm(FlowTaskForm flowTaskForm) {
		this.flowTaskForm = flowTaskForm;
	}


    
    
}
